<template>
  <el-drawer :model-value="visible" :title="`关联房间锁`" size="30%" append-to-body lock-scroll @close="handleClose">
    <section style="height: calc(100% - 200px);overflow-y: auto;" ref="listRef">
      <TaiTitle title="房间" class="mb20"></TaiTitle>
      <template v-if="list.length > 0">
        <div class="primary-section pv-12" v-for="(item, index) in list" :key="index">
          <div>{{ item.name }}</div>
          <el-icon color="var(--el-color-primary)" style="cursor: pointer;" @click="associateRoom(item)"><Plus /></el-icon>
        </div>
      </template>
      <el-empty v-else />
    </section>
    <pagination
      v-show="total > 0"
      :total="total"
      :small="true"
      layout="prev, pager, next"
      v-model:page="currentPage"
      v-model:limit="pageSize"
      @pagination="handlePagination"
    />
  </el-drawer>
</template>
<script setup name="AssociationRoomDrawer">
import { scrollTo } from '@/utils/scroll-to'
import RoomApi, {getNotBindLockList} from "@/api/room/room.js";
import {Plus} from "@element-plus/icons-vue";
import LockApi from "@/api/device/lock.js";

const { proxy } = getCurrentInstance()

const emit = defineEmits()
const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  lockId: {
    type: [String, Number],
    default: () => {
      return ''
    }
  },
})

const loading = ref(false)
const total = ref(0)

const search = ref('')
// const visible = ref(false)
const list = ref([])

const currentPage = computed({
  get() {
    return props.page
  },
  set(val) {
    emit('update:page', val)
  }
})
const pageSize = computed({
  get() {
    return props.limit
  },
  set(val){
    emit('update:limit', val)
  }
})
function handlePagination() {
  emit('pagination', { page: currentPage.value, limit: pageSize.value })
  proxy.$refs['listRef'].scrollTop = 0
}

/* 绑定房间 */
function associateRoom(room) {
  if (!props.lockId || props.lockId === '') {
    proxy.$modal.msgWarning('请重新选择设备')
    return
  }
  LockApi.bindRoom({
    lockId: props.lockId,
    roomId: room.roomId
  }).then(res => {
    proxy.$modal.msgSuccess('操作成功')
    emit('bind-complete')
  })
}

/* 关闭窗口 */
function handleClose() {
  emit('cancel')
}

function getList() {
  list.value = []
  total.value = 0
  loading.value = true
  RoomApi.getNotBindLockList().then(res => {
    list.value = res.rows
    total.value = res.total
    loading.value = false
  })
}

getList()
</script>
<style lang="scss" scoped>
.primary-section {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
</style>